<template>
  <div class="access-control-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="设备名称" style="width: 100%">
              <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="设备型号" style="width: 100%">
              <el-input v-model="searchForm.deviceModel" placeholder="请输入设备型号" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="配置状态" style="width: 100%">
              <el-select v-model="searchForm.configStatus" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="连接状态" style="width: 100%">
              <el-select v-model="searchForm.connectTestResult" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="成功" :value="1" />
                <el-option label="失败" :value="0" />
                <el-option label="未测试" :value="null" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7" class="mt-2">
            <el-form-item label="创建时间" style="width: 100%">
              <el-date-picker v-model="searchForm.createTime" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4" class="mt-2">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon class="el-icon--left">
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button @click="resetSearch">
              <el-icon class="el-icon--left">
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <el-button type="primary" @click="handleAdd">
        <el-icon class="el-icon--left">
          <Plus />
        </el-icon>
        新增配置
      </el-button>
      <el-table :data="tableData" v-loading="loading" border style="width: 100%" class="mt-2"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="id" label="配置ID" align="center" />

        <el-table-column prop="deviceName" label="设备名称" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="device-info">
              <span class="device-name">{{ row.deviceName || '-' }}</span>
              <el-tag v-if="row.deviceModel" size="small" effect="plain" class="model-tag">
                {{ row.deviceModel }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="deviceUrl" label="设备地址" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.deviceUrl || '-' }}</span>
            <span v-if="row.devicePort">:{{ row.devicePort }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="loginUsername" label="登录用户" align="center">
          <template #default="{ row }">
            <span>{{ row.loginUsername || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="configStatus" label="配置状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getConfigStatusTag(row.configStatus)" size="small">
              {{ getConfigStatusText(row.configStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="connectTestResult" label="连接状态" align="center">
          <template #default="{ row }">
            <div class="connection-status">
              <el-tag :type="getConnectionStatusTag(row.connectTestResult)" size="small">
                {{ getConnectionStatusText(row.connectTestResult) }}
              </el-tag>
              <span v-if="row.connectTestTime" class="test-time">
                {{ formatTime(row.connectTestTime) }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="configRemark" label="备注" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.configRemark || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.updateTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="280">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" link size="small" @click="handleTestConnection(row)">
              测试
            </el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button v-if="row.configStatus === 1" type="info" link size="small" @click="handleToggleStatus(row, 0)">
              禁用
            </el-button>
            <el-button v-if="row.configStatus === 0" type="success" link size="small"
              @click="handleToggleStatus(row, 1)">
              启用
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tableData.length > 0">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <div v-if="tableData.length === 0" class="empty-table">
        <el-empty description="暂无数据" :image-size="80" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="config-form">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备选择" prop="deviceId">
                  <el-select v-model="formData.deviceId" placeholder="请选择门禁设备" filterable style="width: 100%"
                    @change="handleDeviceChange">
                    <el-option v-for="device in deviceOptions" :key="device.deviceId"
                      :label="`${device.deviceName} (${device.deviceIp})`" :value="device.deviceId"
                      :disabled="device.deviceStatus === 0">
                      <div class="device-option">
                        <span class="device-name">{{ device.deviceName }}</span>
                        <span class="device-ip">{{ device.deviceIp }}</span>
                        <el-tag :type="device.deviceStatus === 1 ? 'success' : 'danger'" size="small">
                          {{ device.deviceStatus === 1 ? '在线' : '离线' }}
                        </el-tag>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="设备型号" prop="deviceModel">
                  <el-input v-model="formData.deviceModel" placeholder="请输入设备型号" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="设备名称" prop="deviceName">
                  <el-input v-model="formData.deviceName" placeholder="请输入设备名称" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="设备地址" prop="deviceUrl">
                  <el-input v-model="formData.deviceUrl" placeholder="请输入设备IP或域名" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="通信端口" prop="devicePort">
                  <el-input-number v-model="formData.devicePort" :min="1" :max="65535" placeholder="请输入端口号"
                    controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="登录用户" prop="loginUsername">
                  <el-input v-model="formData.loginUsername" placeholder="请输入登录用户名" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="登录密码" prop="loginPassword">
                  <el-input v-model="formData.loginPassword" type="password" placeholder="请输入登录密码" show-password
                    style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="配置状态">
                  <el-switch v-model="formData.configStatus" :active-value="1" :inactive-value="0" active-text="启用"
                    inactive-text="禁用" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 高级配置 -->
          <el-tab-pane label="高级配置" name="advanced">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="配置备注">
                  <el-input v-model="formData.configRemark" type="textarea" :rows="4" placeholder="请输入配置备注信息"
                    maxlength="500" show-word-limit />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="连接参数">
                  <div class="connection-params">
                    <el-descriptions :column="2" border size="small">
                      <el-descriptions-item label="完整地址">
                        {{ getFullDeviceUrl }}
                      </el-descriptions-item>
                      <el-descriptions-item label="连接状态">
                        <el-tag :type="getConnectionStatusTag(formData.connectTestResult)" size="small">
                          {{ getConnectionStatusText(formData.connectTestResult) }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="最后测试">
                        {{ formData.connectTestTime ? formatDateTime(formData.connectTestTime) : '未测试' }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 连接测试 -->
          <el-tab-pane label="连接测试" name="test">
            <div class="test-section">
              <div class="test-header">
                <h4>连接测试</h4>
                <el-button type="primary" @click="handleTestConnection(formData)" :loading="testing">
                  <el-icon>
                    <Connection />
                  </el-icon>
                  立即测试
                </el-button>
              </div>

              <div class="test-result" v-if="testResult">
                <el-alert :title="testResult.title" :type="testResult.type" :description="testResult.message" show-icon
                  :closable="false" />
              </div>

              <div class="test-tips">
                <h5>测试说明：</h5>
                <ul>
                  <li>测试将验证设备地址、端口、用户名和密码的正确性</li>
                  <li>测试成功表示可以正常连接到门禁设备</li>
                  <li>测试失败请检查网络连接和设备参数</li>
                </ul>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ dialogType === 'add' ? '新增' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="配置详情" width="700px" :before-close="handleCloseViewDialog">
      <div v-if="currentDetail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="配置ID">{{ currentDetail.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ currentDetail.deviceId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ currentDetail.deviceModel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ currentDetail.deviceName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备地址">
            {{ currentDetail.deviceUrl || '-' }}
            <span v-if="currentDetail.devicePort">:{{ currentDetail.devicePort }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="登录用户">{{ currentDetail.loginUsername || '-' }}</el-descriptions-item>
          <el-descriptions-item label="配置状态">
            <el-tag :type="getConfigStatusTag(currentDetail.configStatus)" size="small">
              {{ getConfigStatusText(currentDetail.configStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="连接状态">
            <el-tag :type="getConnectionStatusTag(currentDetail.connectTestResult)" size="small">
              {{ getConnectionStatusText(currentDetail.connectTestResult) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后测试">
            {{ currentDetail.connectTestTime ? formatDateTime(currentDetail.connectTestTime) : '未测试' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updateTime) || '-'
          }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions v-if="currentDetail.configRemark" title="备注信息" :column="1" border class="mt-3">
          <el-descriptions-item label="备注">
            <div class="remark-content">{{ currentDetail.configRemark }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="handleCloseViewDialog">关闭</el-button>
        <el-button type="primary" @click="handleEdit(currentDetail)" v-if="currentDetail">
          编辑
        </el-button>
        <el-button type="success" @click="handleTestConnection(currentDetail)" v-if="currentDetail">
          连接测试
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 图标引入
import {
  Search,
  Refresh,
  Plus,
  Connection,
  Open,
  TurnOff,
  Delete,
  View,
  Edit
} from '@element-plus/icons-vue'

// API引入
import {
  getAccessDeviceList,
  getVideoAccessConfigList,
  getVideoAccessConfigDetail,
  addVideoAccessConfig,
  updateVideoAccessConfig,
  deleteVideoAccessConfig,
  testConnection
} from '@/api/park/base_setting'

// 搜索表单
const searchForm = reactive({
  deviceName: '',
  deviceModel: '',
  configStatus: '',
  connectTestResult: '',
  createTime: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)
const submitting = ref(false)
const testing = ref(false)

// 设备选项
const deviceOptions = ref([])

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const activeTab = ref('basic')

// 当前详情
const currentDetail = ref(null)

// 测试结果
const testResult = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  id: '',
  deviceId: '',
  deviceModel: '',
  deviceName: '',
  deviceUrl: '',
  devicePort: 80,
  loginUsername: '',
  loginPassword: '',
  configRemark: '',
  configStatus: 1,
  connectTestResult: null,
  connectTestTime: ''
})

// 表单验证规则
const formRules = {
  deviceId: [
    { required: true, message: '请选择门禁设备', trigger: 'change' }
  ],
  deviceModel: [
    { required: true, message: '请输入设备型号', trigger: 'blur' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  deviceUrl: [
    { required: true, message: '请输入设备地址', trigger: 'blur' },
    { pattern: /^((https?|ftp):\/\/)?([\da-z.-]+)\.([a-z.]{2,6})(\/\w\.-]*)*\/?$|^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入正确的IP地址或域名', trigger: 'blur' }
  ],
  devicePort: [
    { required: true, message: '请输入通信端口', trigger: 'blur' }
  ],
  loginUsername: [
    { required: true, message: '请输入登录用户名', trigger: 'blur' }
  ],
  loginPassword: [
    { required: true, message: '请输入登录密码', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增视频门禁配置' : '编辑视频门禁配置'
})

const getFullDeviceUrl = computed(() => {
  if (!formData.deviceUrl) return '-'
  return formData.devicePort ? `${formData.deviceUrl}:${formData.devicePort}` : formData.deviceUrl
})

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      loadDeviceList(),
      loadConfigList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 加载设备列表
const loadDeviceList = async () => {
  try {
    const res = await getAccessDeviceList()
    deviceOptions.value = res.data || []
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error('加载设备列表失败')
  }
}

// 加载配置列表
const loadConfigList = async () => {
  try {
    loading.value = true

    const params = {
      deviceName: searchForm.deviceName,
      deviceModel: searchForm.deviceModel,
      configStatus: searchForm.configStatus,
      connectTestResult: searchForm.connectTestResult,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 处理时间范围
    if (searchForm.createTime && searchForm.createTime.length === 2) {
      params.startCreateTime = searchForm.createTime[0]
      params.endCreateTime = searchForm.createTime[1]
    }

    const res = await getVideoAccessConfigList(params)

    tableData.value = res.rows || []
    pagination.total = res.total || 0
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  loadConfigList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    deviceName: '',
    deviceModel: '',
    configStatus: '',
    connectTestResult: '',
    createTime: ''
  })
  pagination.currentPage = 1
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadConfigList()
  ElMessage.success('数据已刷新')
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增配置
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getVideoAccessConfigDetail(row.id)
    currentDetail.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 编辑配置
const handleEdit = async (row) => {
  try {
    const res = await getVideoAccessConfigDetail(row.id)
    dialogType.value = 'edit'
    Object.assign(formData, res.data)
    dialogVisible.value = true
    viewDialogVisible.value = false
  } catch (error) {
    console.error('获取编辑数据失败:', error)
    ElMessage.error('获取编辑数据失败')
  }
}

// 删除配置
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${row.deviceName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteVideoAccessConfig(row.id)
    ElMessage.success('删除成功')
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(item => item.id).join(',')
    await deleteVideoAccessConfig(ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 连接测试
const handleTestConnection = async (config) => {
  try {
    testing.value = true
    testResult.value = null

    const res = await testConnection(config.id)
    testResult.value = {
      type: 'success',
      title: '连接测试成功',
      message: '设备连接正常，参数配置正确'
    }
    ElMessage.success('连接测试成功')

    // 更新配置信息
    if (dialogType.value === 'edit') {
      const detailRes = await getVideoAccessConfigDetail(config.id)
      Object.assign(formData, detailRes.data)
    }

    // 刷新列表
    loadConfigList()
  } catch (error) {
    console.error('连接测试失败:', error)
    testResult.value = {
      type: 'error',
      title: '连接测试失败',
      message: error.message || '网络错误，请稍后重试'
    }
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 批量测试
const handleBatchTest = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要测试的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要对选中的 ${selectedRows.value.length} 条记录进行连接测试吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    let successCount = 0
    for (const row of selectedRows.value) {
      try {
        const res = await testConnection(row.id)
        successCount++
      } catch (error) {
        console.error(`测试配置 ${row.deviceName} 失败:`, error)
      }
    }

    ElMessage.success(`批量测试完成，成功 ${successCount}/${selectedRows.value.length}`)
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量测试失败:', error)
      ElMessage.error('批量测试失败')
    }
  }
}

// 启用/禁用配置
const handleToggleStatus = async (row, status) => {
  try {
    const actionText = status === 1 ? '启用' : '禁用'
    await ElMessageBox.confirm(
      `确定要${actionText}配置 "${row.deviceName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const updateData = { ...row, configStatus: status }
    await updateVideoAccessConfig(updateData)
    ElMessage.success(`${actionText}成功`)
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 批量启用
const handleBatchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要启用的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const row of selectedRows.value) {
      const updateData = { ...row, configStatus: 1 }
      await updateVideoAccessConfig(updateData)
    }

    ElMessage.success('批量启用成功')
    selectedRows.value = []
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
      ElMessage.error('批量启用失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要禁用的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const row of selectedRows.value) {
      const updateData = { ...row, configStatus: 0 }
      await updateVideoAccessConfig(updateData)
    }

    ElMessage.success('批量禁用成功')
    selectedRows.value = []
    loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
      ElMessage.error('批量禁用失败')
    }
  }
}

// 设备选择变化
const handleDeviceChange = (deviceId) => {
  const selectedDevice = deviceOptions.value.find(d => d.deviceId === deviceId)
  if (selectedDevice) {
    formData.deviceName = selectedDevice.deviceName
    formData.deviceUrl = selectedDevice.deviceIp
    // 可以根据设备型号设置默认端口
    if (selectedDevice.deviceModel) {
      formData.deviceModel = selectedDevice.deviceModel
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    deviceId: '',
    deviceModel: '',
    deviceName: '',
    deviceUrl: '',
    devicePort: 80,
    loginUsername: '',
    loginPassword: '',
    configRemark: '',
    configStatus: 1,
    connectTestResult: null,
    connectTestTime: ''
  })
  testResult.value = null
  activeTab.value = 'basic'
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 关闭查看对话框
const handleCloseViewDialog = () => {
  viewDialogVisible.value = false
  currentDetail.value = null
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (dialogType.value === 'add') {
      await addVideoAccessConfig(formData)
      ElMessage.success('配置新增成功')
    } else {
      await updateVideoAccessConfig(formData)
      ElMessage.success('配置更新成功')
    }

    dialogVisible.value = false
    loadConfigList()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadConfigList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadConfigList()
}

// 工具函数
const getConfigStatusTag = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'info'
    default: return 'info'
  }
}

const getConfigStatusText = (status) => {
  switch (status) {
    case 1: return '启用'
    case 0: return '禁用'
    default: return status || '-'
  }
}

const getConnectionStatusTag = (result) => {
  switch (result) {
    case 1: return 'success'
    case 0: return 'danger'
    case null: return 'info'
    default: return 'info'
  }
}

const getConnectionStatusText = (result) => {
  switch (result) {
    case 1: return '成功'
    case 0: return '失败'
    case null: return '未测试'
    default: return result || '-'
  }
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTimeString
  }
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  try {
    return dayjs(timeString).format('MM-DD HH:mm')
  } catch {
    return timeString
  }
}
</script>

<style scoped lang="scss">
.access-control-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  .el-row {
    margin-bottom: 0;
  }
}

.form-actions {
  padding-top: 29px;
  text-align: center;
}

.action-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.device-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-name {
  font-weight: 500;
}

.model-tag {
  font-size: 10px;
  padding: 1px 6px;
}

.connection-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.test-time {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-table {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.config-form {
  .el-tabs {
    margin-top: -20px;
  }
}

.device-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.device-name {
  font-weight: 500;
}

.device-ip {
  color: #909399;
  font-size: 12px;
}

.connection-params {
  margin-top: 8px;
}

.test-section {
  padding: 20px 0;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.test-header h4 {
  margin: 0;
  color: #303133;
}

.test-result {
  margin-bottom: 20px;
}

.test-tips {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.test-tips h5 {
  margin: 0 0 10px 0;
  color: #606266;
}

.test-tips ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
}

.test-tips li {
  margin-bottom: 5px;
  line-height: 1.5;
}

.remark-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

.mt-3 {
  margin-top: 16px;
}
</style>